#include "display.h"

QScopedPointer<display> display::self;

display::display(QObject *parent) : QThread(parent)
{
    initThread();
}

display::~display()
{
    this->stopThread();
    this->wait();
}

void display::initThread()
{
    stopped = false;
    return;
}

display* display::getInstance()
{
    if (self.isNull()) {
        static QMutex mutex;
        QMutexLocker locker(&mutex);
        if (self.isNull()) {
            self.reset(new display);
        }
    }
    return self.data();
}

void display::run()
{
    this->initThread();
    QTime overTime;
    try {
        while (!stopped) {
            overTime = QTime::currentTime().addMSecs(100);
            this->DoThread();
        }
    }catch (cv::Exception &e) {
        qDebug() << e.what();
    }
    while(QTime::currentTime() < overTime) {
        QCoreApplication::processEvents(QEventLoop::AllEvents, 10);
    }
    return;
}

void display::stopThread()
{
    QMutexLocker locker(&mutex_stopped);
    stopped = true;
    return;
}

void display::DoThread()
{
    bool flag;
    QImage img;
    {
        QMutexLocker locker(&Paras::mutexImageShow);
        flag = showImageFlag;
        showImageFlag = false;
        img=QImage((const unsigned char*)(Paras::imageShow.data), Paras::imageShow.cols, Paras::imageShow.rows, QImage::Format_RGB888);
    }
    if (flag) {
        if (ui == nullptr) {
            return;
        }
        if(img.isNull())
            return;
        this->ui->label_display->setPixmap(QPixmap::fromImage(img));
    }
    return;
}

void display::setShowImageFlag(bool flag)
{
    QMutexLocker locker(&Paras::mutexImageShow);
    showImageFlag = flag;
    return;
}

void display::setImage()
{
    {
        QMutexLocker locker2(&Paras::mutexImageShow);
        this->showImageFlag = true;
    }
    return;
}

void display::setParent(QObject *parent)
{
    QMutexLocker locker(&mutex_parent);
    this->parent = parent;
    return;
}

void display::setUI(Ui_visual2* ui)
{
    QMutexLocker locker(&mutex_ui);
    this->ui = ui;
    return;
}